<template>
  <div class="advanced-search__form" v-loading="!fieldList.length">
    <div class="advanced-search__form-item" v-for="(item, index) of searchList" :key="item.id">
      <condition-search-item
        ref="conditionSearchItemRef"
        :fields="fieldList"
        :condition-item="item"
        :remote-method="remoteMethod"
        :module="module"
        @change-value="changeValue(item, $event)"
      />
      <div class="advanced-search__operators">
        <span class="del-icon" @click="removeSearchItem(index)">
          <i class="iconfont icon-delete"></i>
        </span>
        <span>
          <el-checkbox
            v-if="needCommonUse"
            v-model="item.isCommonUse"
            :disabled="!item.fieldName"
            @change="changeCommonUse(item, $event)">
            {{ $t('component.advancedSearch.inCommonUse') }}
          </el-checkbox>
        </span>
      </div>
    </div>
    <div class="advanced-search__add-row">
      <span class="" @click="handleAddRow">+ {{ $t('component.advancedSearch.addSearchCondition') }}</span>
    </div>
    <div class="advanced-search__copy-row" v-if="showUrl">
      <span class="mar-r-10">{{ $t('common.paas.view.designer.rule.visitAddress') }}: </span>
      <el-input disabled v-model="url">
        <el-button type="primary" slot="append" @click="onCopy">{{ $t('common.base.copy') }}</el-button>
      </el-input>
      <el-tooltip :content="$t('component.advancedSearch.copyLinkTip')" placement="top">
        <i class="iconfont icon-question-circle mar-l-8"></i>
      </el-tooltip>
    </div>
  </div>
</template>

<script>
import {
  defineComponent,
  ref,
  watch,
  watchEffect,
} from 'vue';

import ConditionSearchItem from './ConditionSearchItem.vue'

import { createSearchItem, initValue } from './advancedSearch';
import { isEmptyValue } from './searchCondition';

import { cloneDeep } from 'lodash';
import { t } from '@src/locales'
import { Message } from 'element-ui';
/* hooks */
import { setClipboardData } from '@src/util/dom'

export default defineComponent({
  name: 'AdvancedSearchForm',
  components: {
    ConditionSearchItem,
  },
  props: {
    // 字段列表
    fields: {
      type: Array,
      default: () => [],
    },
    // 条件数据
    searchModel: {
      type: Array,
      default: () => [],
    },
    // 远程搜索接口列表
    remoteMethod: {
      type: Object,
      default: () => ({}),
    },
    // 是否需要常用功能
    needCommonUse: {
      type: Boolean,
      default: false,
    },
    // 常用字段
    inCommonUse: {
      type: Array,
      default: () => [],
    },
    // 是否显示访问地址
    showUrl: {
      type: Boolean,
      default: false,
    },
    // 视图访问地址
    url: {
      type: String,
      default: '',
    },
    // 模块
    module: {
      type: String,
      default: '',
    },
  },
  emits: ['change', 'change-search-model'],
  setup(props, { emit }) {
    const conditionSearchItemRef = ref()
    // 搜索条件列表
    const searchList = ref(props.searchModel);
    // 字段列表
    const fieldList = ref([]);
    // 字段map
    let fieldMap = ref({});

    /**
     * 初始表单列表
     */
    function initFields() {
      const list = [];
      fieldMap.value = {};
      props.fields.forEach(item => {
        if (item.fieldName === 'area' && item.formType === 'select') {
          // 客户表单服务器生成的区域字段
          // 原先叫area会去重导致没有添加进去，这里改个名字，在搜索的时候进行转换回area处理
          item.fieldName = 'customerAreaSelect';
        }
        if (!fieldMap.value[item.fieldName]) {
          fieldMap.value[item.fieldName] = item;
          list.push(cloneDeep(item));
        }
      });
      fieldList.value = list;
    }

    /**
     * 初始搜索条件列表
     */
    function initSearchModel(searchModel) {
      if (!fieldList.value.length) return;
      const list = [];
      // 选中的条件set列表
      const searchListFieldSet = new Set([]);
      const inCommonUseSet = new Set(props.inCommonUse || []);
      searchModel.forEach(_item => {
        const field = fieldMap.value[_item.fieldName];
        if (field) {
          const item = createSearchItem(_item);
          // 是否常用字段
          item.isCommonUse = inCommonUseSet.has(field.fieldName); 
          list.push(item);
          searchListFieldSet.add(field.fieldName);
        }
      });

      const isSearchModel = !searchModel.length || (searchModel.length === 1 && !searchModel[0].fieldName)


      if (isSearchModel && props.needCommonUse && inCommonUseSet.size) {
        // 处理常用字段 （有searchModel 代表从视图来的，不处理为显示的常用字段）
        inCommonUseSet.forEach(fieldName => {
          const field = fieldMap.value[fieldName]; // 字段列表中是否存在
          const isInSearchList = searchListFieldSet.has(fieldName); // 是否在条件列表中
          if (!isInSearchList && field) {
            // 常用字段 不在查询列表中药添加一个空的常用条件
            const item = {
              ...createSearchItem(),
            }; // 创建一个新值
            item.fieldName = field.fieldName // 初始化传入field 来选中初始字段
            item.isCommonUse = true;
            list.push(item);
          }
        });
        
      }
      
      
      // 设置条件列表
      searchList.value = list;

      // 新建没有默认添加一个
      if (searchList.value.length === 0) {
        searchList.value.push(createSearchItem());
      }
    }

    /**
     * 改变值
     */
    function changeValue(value) {
      emit('change', item);
    }

    /**
     * 添加条件
     */
    function handleAddRow() {
      searchList.value.push(createSearchItem());
    }

    /**
     * 移出单个条件
     */
    function removeSearchItem(index) {
      searchList.value.splice(index, 1);
      if (!searchList.value.length) {
        handleAddRow();
      }
      // 监听删除后搜索条件的变化
      // emit('monitor-delete-search-modal', searchList.value)
    }

    /**
     * 恢复视图默认
     */
    function reset() {
      searchList.value = [];
      initSearchModel(props.searchModel);
    }
    /**
     * 清除所有值
     */
    function clear() {
      searchList.value.forEach(item => {
        if (item.field) {
          item.value = initValue(item);
        }
      });
    }

    /**
     * 获取搜索条件
     */
    function getSearchList() {
      return searchList.value.filter(item => !isEmptyValue(item.value));
    }

    /**
     * 切换常用
     * @param {*} item
     * @param {*} isChecked
     */
    function changeCommonUse(item, isChecked, isDeep = true) {
      emit('changeCommonUse', {
        fieldName: item.fieldName,
        isChecked,
      });
      if (isDeep) {
        searchList.value.map(searchItem => {
          if (item.fieldName === searchItem.fieldName && item !== searchItem) {
            searchItem.isCommonUse = isChecked;
            changeCommonUse(searchItem, isChecked, false);
          }
        });
      }
    }

    // 复制链接
    function onCopy() {
      setClipboardData(
        props.url,
        () => {
          Message.success(t('common.base.tip.copySuccess'));
        },
        () => {
          Message.warning(t('common.base.tip.copyFail'));
        }
      )
    }

    {
      watch(
        () => props.fields,
        () => {
          initFields();
          // 初始化搜索条件列表
          initSearchModel(searchList.value);
        },
        {
          immediate: true,
        }
      );

      watch(
        () => props.searchModel,
        () => {
          // 切换视图会触发
          searchList.value = [];
          // 初始化搜索条件列表
          initSearchModel(props.searchModel);
        }
      );

      watchEffect(() => {
        // 改变条件列表
        emit('change-search-model', getSearchList());
      });

    }

    return {
      conditionSearchItemRef,
      fieldList,
      searchList,
      changeValue,
      reset,
      clear,
      handleAddRow,
      removeSearchItem,

      getSearchList, // 业务调用此方法得到表单列表
      changeCommonUse,
      onCopy,
    };
  },
});
</script>

<style lang="scss">
.advanced-search__form {
  // min-width: 550px;
  width: 100%;

  .advanced-search__form-item {
    margin-bottom: 12px;
    display: flex;
    align-items: center;

    .advanced-search__operators {
      &>* {
        margin-left: 8px;
      }

      .del-icon {
        color: $text-color-secondary;
        cursor: pointer;

        &:hover {
          color: $color-danger;
        }
      }
    }
  }

  .advanced-search__add-row {
    color: $color-primary;
    cursor: pointer;
    margin-bottom: 28px;

    &:hover {
      opacity: 0.9;
    }
  }

  .advanced-search__copy-row {
    display: flex;
    align-items: center;
    span {
      width: 70px;
    }
    .el-input {
      flex: 1;
    }
  }
}
</style>
